package cn.xmoit.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 授权服务器配置
 *
 * @author fangyy
 */
// @Configuration
// @EnableAuthorizationServer
public class OAuth2AuthorizationServerJwtConfig extends AuthorizationServerConfigurerAdapter {

	/**
	 * 用户认证 Manager
	 */
	@Autowired
	private AuthenticationManager authenticationManager;

	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter() {
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		// JWT 秘钥
		converter.setSigningKey("jwt_secret");
		return converter;
	}

	@Bean
	public JwtTokenStore jwtTokenStore() {
		return new JwtTokenStore(jwtAccessTokenConverter());
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager)
			.tokenStore(jwtTokenStore())
			.accessTokenConverter(jwtAccessTokenConverter());
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.checkTokenAccess("isAuthenticated()");
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		// 1.不具备刷新令牌的写法
		// clients.inMemory().withClient("test").secret("123456").authorizedGrantTypes("password").scopes("read_userinfo","read_contacts");

		// 2.带刷新令牌的写法
		clients.inMemory()
			// Client 账号
			.withClient("test")
			// Client 密码
			.secret("123456")
			// 授权码模式
			.authorizedGrantTypes("password", "authorization_code", "refresh_token")
			.redirectUris("http://127.0.0.1:8080/login", "http://a.com:8081/login", "http://b.com:8082/login")
			// 可授权的 Scope
			.scopes("read_userinfo", "read_contacts")
			.accessTokenValiditySeconds(3600)
			.refreshTokenValiditySeconds(864000);
	}

}